
<template>
  <!-- 用户授权页面 -->
  <div>
    <el-row class="caliberHierarchy container" :gutter="10">
      <el-col :span="16" class="content-left">
        <el-row class="handleBox">
          <el-col :span="18" />
          <el-col :span="6">
            <div class="handleIconBox">
              <el-popover
                placement="bottom"
                trigger="click"
                popper-class="icon_porper"
              >
                <div class="search_porper">
                  <el-form
                    ref="searchForm"
                    :model="searchForm"
                    label-width="90px"
                    label-position="left"
                    size="mini"
                  >
                    <el-form-item label="姓　　名：">
                      <el-input
                        v-model.trim="searchForm.realName"
                        style="width: 150px"
                        @keydown.enter.native="searchFunc()"
                      />
                    </el-form-item>
                    <el-form-item label="用 户 名：" prop="userName">
                      <el-input
                        v-model.trim="searchForm.userName"
                        style="width: 150px"
                        @keydown.enter.native="searchFunc()"
                      />
                    </el-form-item>
                    <el-form-item label="所属机构：" prop="orgId">
                      <el-tooltip
                        :content="searchOrgTip"
                        :disabled="!searchOrgTip"
                        placement="right-end"
                        class="item"
                      >
                        <el-cascader
                          ref="searchOrgTree"
                          v-model="searchForm.orgId"
                          clearable
                          filterable
                          :options="orgList"
                          :props="{
                            checkStrictly: true,
                            emitPath: false,
                            value: 'orgId',
                            label: 'orgName',
                          }"
                          :show-all-levels="false"
                          style="width: 150px"
                          @change="searchOrgHandle"
                        />
                      </el-tooltip>
                    </el-form-item>
                  </el-form>
                  <div style="text-align: center; padding: 10px">
                    <el-button
                      size="mini"
                      @click="(searchForm.page = 1), searchFunc()"
                      >查询</el-button
                    >
                    <el-button size="mini" @click="clearSearch(searchForm)"
                      >重置</el-button
                    >
                  </div>
                </div>
                <i slot="reference" class="iconfont icon-sousuo" title="搜索" />
              </el-popover>
              <el-popover
                placement="bottom"
                width="150"
                trigger="click"
                popper-class="icon_porper"
              >
                <div class="operation_checkbox">
                  <el-checkbox-group v-model="checkList">
                    <el-checkbox
                      v-for="item in textData"
                      :key="item.prop"
                      :label="item.label"
                      >{{ item.label }}
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
                <i
                  slot="reference"
                  class="iconfont icon-liebiaoshezhi"
                  title="列表设置"
                />
              </el-popover>
            </div>
          </el-col>
        </el-row>
        <el-table
          ref="multipleTable"
          :data="tableData"
          style="width: 100%"
          @row-click="getItemTable"
        >
          <el-table-column width="55" type="selection" />
          <el-table-column
            v-if="columnState[0]"
            prop="userName"
            label="用户名"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnState[1]"
            prop="realName"
            label="用户姓名"
            sortable
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnState[2]"
            prop="org.orgName"
            label="机构"
            sortable
            show-overflow-tooltip
          />
        </el-table>
        <pagination
          :current-page="searchForm.page"
          :page-size="searchForm.size"
          :total="total"
          @size-change="sizeChange"
          @current-change="pageChange"
          @refresh="searchFunc"
        />
      </el-col>
      <el-col :span="8" class="content-right">
        <upper-template no-icon>
          <div slot="buttonArea">
            <el-button @click="authorization('authorization')">授权</el-button>
            <el-button @click="authorization('unauthorization')"
              >撤销</el-button
            >
            <el-button @click="setDefaultProject">设为默认</el-button>
          </div>
        </upper-template>
        <el-table
          ref="dictItemTable"
          :data="dictItemTable"
          style="width: 100%"
          class="isRightTable"
          @row-click="rowClickItemTable"
        >
          <el-table-column width="55" type="selection" />
          <el-table-column
            v-if="columnStateR[0]"
            prop="tenantDTO.tenantName"
            label="所属租户"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnStateR[1]"
            prop="projectName"
            label="工程名称"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnStateR[2]"
            prop="grantStatus"
            label="授权状态"
            align="center"
          >
            <template slot-scope="scope">
              <div v-if="scope.row.grantStatus == 1">
                <i class="startState" />已授权
              </div>
              <div v-if="scope.row.grantStatus != 1">
                <i class="unStartState" />未授权
              </div>
            </template>
          </el-table-column>
          <el-table-column
            v-if="columnStateR[3]"
            prop="isDefault"
            label="是否默认"
            align="center"
          >
            <template slot-scope="scope">
              <div v-if="scope.row.isDefault == 1">
                <i class="startState" />是
              </div>
              <div v-if="scope.row.isDefault != 1">
                <i class="unStartState" />否
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <!-- 新增/编辑字典类型 -->
  </div>
</template>

<script>
import { systemManage } from "@/api/index";
import { getDict } from "@/api/getDict";
export default {
  data() {
    return {
      // search机构树悬停提示
      searchOrgTip: "",
      orgList: [],
      addOrEdit: false, // 新增/编辑字典弹窗
      isItemVisible: false, // 新增/编辑字典项弹窗
      saveFlg: 1, // 1:新增，2：编辑，（字典）
      saveItemFlg: 1, // 1:新增，2：编辑 （字典项）
      saveDictTitles: ["新增字典类型", "编辑字典类型"],
      saveItemTitles: ["新增字典项", "编辑字典项"],
      // 所属模块下拉框
      moduleList: [],
      // 状态字典
      statusList: [],
      // save表单机构树悬停提示
      saveOrgTip: "",
      searchForm: {
        page: 1,
        size: 15,
      },
      total: 0,
      saveForm: {
        moduleCode: "",
        typeId: "",
        typeName: "",
      },
      saveItemForm: {
        typeId: "",
        itemId: "",
        itemName: "",
        sortNo: "",
        status: "",
      },
      checkList: [],
      checkListRight: [],
      // 完整表头字段
      textData: [
        { label: "用户名" },
        { label: "用户姓名" },
        { label: "机构" },
        // { label: '状态' }
      ],
      // 右侧字段
      textDataRight: [
        { label: "所属租户", disabled: true },
        { label: "工程名称", disabled: true },
        { label: "授权状态" },
        { label: "是否默认" },
      ],
      // 获取table的数据
      tableData: [],
      dictItemTable: [],
      searchFormItem: {
        status: "",
        page: 1,
        size: 999,
      },
      totalItem: 0,
    };
  },
  computed: {
    columnState() {
      const arr = [];
      const arr1 = this.textData;
      const arr2 = this.checkList;
      for (let i = 0; i < arr1.length; i++) {
        let flg = false;
        for (let j = 0; j < arr2.length; j++) {
          if (arr1[i].label === arr2[j]) {
            flg = true;
          }
        }
        arr.push(flg);
      }
      return arr;
    },
    columnStateR() {
      const arr = [];
      const arr1 = this.textDataRight;
      const arr2 = this.checkListRight;
      for (let i = 0; i < arr1.length; i++) {
        let flg = false;
        for (let j = 0; j < arr2.length; j++) {
          if (arr1[i].label === arr2[j]) {
            flg = true;
          }
        }
        arr.push(flg);
      }
      return arr;
    },
  },
  watch: {
    addOrEdit() {
      // 窗口打开或关闭清除校验结果
      console.log("waa");
      if (this.$refs.saveForm) {
        this.$refs.saveForm.clearValidate();
      }
    },
    isItemVisible() {
      // 窗口打开或关闭清除校验结果
      if (this.$refs.saveItemForm) {
        this.$refs.saveItemForm.clearValidate();
      }
    },
  },
  created() {
    this.checkListInit();
    this.getDIct();
    this.$nextTick(() => {
      this.searchFunc();
    });
  },
  mounted() {},
  methods: {
    // 获取字典
    getDIct() {
      // 启用锁定字典
      getDict("sys_userFlg").then((res) => {
        console.log(res, "字典启用");
        if (res.code == 200) {
          this.statusList = res.datas;
        }
      });
      systemManage.getOrganTree().then((res) => {
        console.log(res, "机构");
        this.orgList = res;
      });
    },
    // 处理搜索机构框点击选中隐藏,鼠标悬停提示
    searchOrgHandle() {
      this.$refs.searchOrgTree.dropDownVisible = false;
      const node = this.$refs.searchOrgTree.getCheckedNodes();
      if (node.length != 0) {
        this.searchOrgTip = node[0].label;
      } else {
        this.searchOrgTip = "";
      }
    },
    clearSearch(obj) {
      for (const key in obj) {
        obj[key] = "";
      }
      obj.page = 1;
      obj.size = 15;
    },
    checkListInit() {
      this.checkList = this.textData.map((v) => {
        return v.label;
      });
      this.checkListRight = this.textDataRight.map((v) => {
        return v.label;
      });
    },
    // 用户查询
    searchFunc() {
      const data = this.searchForm;
      systemManage.queryUserForPageForProject(data).then((res) => {
        if (res.code == 200) {
          this.tableData = res.datas.rows;
          this.total = res.datas.total;
          // 右侧默认显示第一个字典类型的字典项
          this.$nextTick(() => {
            if (this.tableData.length > 0) {
              this.getItemTable(this.tableData[0]);
            }
          });
        }
      });
    },
    searchFuncItem() {
      this.getItemTable(this.clickRow);
    },
    authorization(str) {
      const selection = this.$refs.dictItemTable.selection;
      if (selection.length < 1) {
        return this.$message.warning("请选择数据");
      }
      this.$confirm(
        "您确定要" +
          (str == "authorization" ? "授权" : "撤销") +
          "选中的数据吗？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          let data = {
            projectIds: selection.map((v) => v.projectId),
            userId: this.clickRow.userId,
          };
          // 授权
          if (str == "authorization") {
            data.grantStatus = "1";
          } else {
            // 撤销
            data.grantStatus = "0";
          }
          systemManage.grantUserProjects(data).then((res) => {
            if (res && res.code == 200) {
              this.$message.success(
                (str == "authorization" ? "授权" : "撤销") + "成功"
              );
              this.searchFunc();
            } else {
              this.$message.error(res.message || "失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },

    // 设置用户默认工程
    setDefaultProject() {
      const selection = this.$refs.dictItemTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据");
      }
      this.$confirm("您确定要设置该数据为默认工程吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const data = {
            userId: this.clickRow.userId,
            projectId: selection[0].projectId,
          };
          systemManage.setDefaultProject(data).then((res) => {
            if (res && res.code == 200) {
              this.$message.success("成功");
              this.searchFunc();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    // 点击表格右侧显示字典项
    getItemTable(row) {
      console.log(row);
      if (this.$refs.multipleTable) {
        this.$refs.multipleTable.clearSelection();
      }
      this.$refs.multipleTable.toggleRowSelection(row, true);
      this.clickRow = row;
      const param = { id: row.userId };
      // 通过用户查询用户下的工程
      systemManage.getProjectsByUserID(param).then((res) => {
        if (res && res.code == 200) {
          this.dictItemTable = res.datas;
          // 后台查出顺序乱的，排下序
          this.dictItemTable.sort((x, y) => {
            return x.sortNo - y.sortNo;
          });
          this.totalItem = res.datas.total;
        }
      });
    },
    rowClickItemTable(row) {
      if (this.$refs.dictItemTable) {
        this.$refs.dictItemTable.clearSelection();
      }
      this.$refs.dictItemTable.toggleRowSelection(row, true);
    },
    sizeChange(val) {
      this.searchForm.size = val;
      this.searchFunc();
      console.log(`每页 ${val} 条`);
    },
    pageChange(val) {
      this.searchForm.page = val;
      this.searchFunc();
      console.log(`当前页: ${val}`);
    },
    sizeChangeItem(val) {
      this.searchFormItem.size = val;
      this.searchFuncItem();
      console.log(`每页 ${val} 条`);
    },
    pageChangeItem(val) {
      this.searchFormItem.page = val;
      this.searchFuncItem();
      console.log(`当前页: ${val}`);
    },
  },
};
</script>

<style lang="scss" scoped>
</style>
